<template>
    <div>
        <a-form
            ref="loginFormRef"
            class="login"
            :model="formState"
            name="login-form"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
            autocomplete="off"
        >
            <a-form-item
                class="login__field"
                name="account"
                :rules="[{ required: true, message: '请输入姓名!' }]"
                >
                <a-input class="login__input" v-model:value="formState.account" style="width: 100%;" placeholder="请输入账户">
                    <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
                </a-input>
            </a-form-item>

            <a-form-item
                class="login__field"
                name="password"
                :rules="[{ required: true, message: '请输入密码!' }]"
                >
                <a-input-password class="login__input" v-model:value="formState.password" style="width: 100%;" placeholder="请输入密码">
                    <template #prefix>
                        <LockOutlined style="color: rgba(0, 0, 0, 0.25)"/>
                    </template>
                </a-input-password>
            </a-form-item>

            <a-form-item
                class="login__field"
                name="code"
                :rules="[{ required: true, message: '请输入验证码!' }]"
            >
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-input class="login__input" v-model:value="formState.code" style="width: 100%;" placeholder="请输入验证码" :maxlength="4"/>
                </a-col>
                <a-col :span="12">
                    <div :class="[state.expirySeconds > 0 ? 'login-content-code' : 'login-content-code-expired']" @click="getCaptcha">
						<img class="login-content-code-img" width="130px" height="38px" :src="state.captchaImage" style="cursor: pointer" />
					</div>
                </a-col>
            </a-row>
            </a-form-item>

            <a-form-item>
                <a-button class="login__submit" ype="primary" @click="submit">
                    登录
                </a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script setup lang="ts">
import { reactive,onMounted,ref,onUnmounted,withDefaults} from 'vue';
import {apiSysAuthCaptchaGet,loginAPI} from '@/api/sys/sysAuth.ts'
import {showMsg} from '@/utils/index'
// import { sm2 } from 'sm-crypto-v2';
import {sm2} from 'sm-crypto'
import type {TenantInfoType } from '../types/index'
import type {ResType} from '@/api/types/index'
import {TOKEN_KEY,REFRESH_ACCESS_TOKEN_KEY} from '@/const/index'
import {Local,Session} from '@/utils/index'
import {initBackEndControlRoutes} from '@/router/background'
import {useRouter,useRoute} from 'vue-router'

interface PropsType {
    tenantInfo:TenantInfoType
}
const props = withDefaults(defineProps<PropsType>(),{})

interface FormState {
    account: string;
    password: string;
    code: string,
    codeId:number | null,
    tenantId:undefined | number | string
}
const router = useRouter()
const route = useRoute()
const loginFormRef = ref()
const formState = reactive<FormState>({
    account: 'superadmin',
    password: '123456',
    code:"",
    codeId:null,
    tenantId:""
});

const state = reactive({
    captchaImage:"",
    expirySeconds:0,
    codeId:"",
})
interface Result {
    accessToken:string,
    refreshToken:string,
}
const saveTokenAndInitRoutes = async (res:Result)=>{
    Local.set(TOKEN_KEY,res.accessToken)
    Local.set(REFRESH_ACCESS_TOKEN_KEY,res.refreshToken)
    Session.set(TOKEN_KEY,res.accessToken)
    Session.set(REFRESH_ACCESS_TOKEN_KEY,res.refreshToken)
    
    // 登录必须先注册路由后跳转
    let isNoPower = await initBackEndControlRoutes()
    
    if(isNoPower){
        showMsg("您没有权限访问后台管理系统",'warning')
        Local.clear()
        Session.clear()
    }else {
        if(route.query.redirect){
        	// 存在重定向
            router.push({
                path: route.query.redirect as string, // 重定向的路由
                query:Object.keys(<string>route.query.params).length>0? JSON.parse(<string>route.query.params) : ""
            })
        }else {
            router.push('/dashboard/home')
        }
        showMsg("登录成功!",'success')
    }
}

const submit = () => {
    loginFormRef.value.validate().then(async()=>{
        const publicKey = import.meta.env.VITE_SM_PUBLIC_KEY
        // 加密
        const password = sm2.doEncrypt(formState.password,publicKey,1)
        formState.tenantId = props.tenantInfo.id

        const res = await loginAPI({...formState,password}) as ResType<Result>

        if(res.data.code == 200){
            await saveTokenAndInitRoutes(res.data.result)
        }else{
            showMsg(res.data.message,'error')
        }
    })
};

const getCaptcha = async()=>{
    formState.code = ''
    let res:any = await apiSysAuthCaptchaGet()
    state.captchaImage = 'data:text/html;base64,' + res.data.result.img
    state.expirySeconds = res.data.result.expirySeconds
    formState.codeId = res.data.result.id
}
const resetForm = () => {
    // loginFormRef.value
};

onMounted(async()=>{
    getCaptcha()
})

onUnmounted(()=>{
    resetForm()
})
</script>

<style lang="scss" scoped>

.login {
	width: 100%;
	padding: 30px;
    margin-top: 30px;
}

.login__field {	
	position: relative;	
}

.login__icon {
	position: absolute;
	top: 30px;
	color: #7875B5;
}

.login__input {
	border: none;
	border-bottom: 2px solid #D1D1D4;
	background: none;
	padding: 10px;
	padding-left: 24px;
	font-weight: 700;
	width: 75%;
	transition: .2s;
}

.login__input:active,
.login__input:focus,
.login__input:hover {
	outline: none;
	border-bottom-color: #6A679E;
}

.login__submit {
    margin-top: 10px;
	background: #fff;
	font-size: 14px;
	border-radius: 26px;
	text-transform: uppercase;
	font-weight: 700;

	width: 100%;
	color: #4C489D;
	box-shadow: 0px 2px 2px #5C5696;
	cursor: pointer;
	transition: .2s;
}

.login-content-code {
		display: flex;
		align-items: center;
		justify-content: space-around;
		position: relative;

		.login-content-code-img {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background-color: #ffffff;
			border: 1px solid rgb(220, 223, 230);
			cursor: pointer;
			transition: all ease 0.2s;
			border-radius: 4px;
			user-select: none;

			&:hover {
				border-color: #c0c4cc;
				transition: all ease 0.2s;
			}
		}
	}

	.login-content-code-expired {
		@extend .login-content-code;
		&::before {
			content: '验证码已过期';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			border-radius: 4px;
			background-color: rgba(0, 0, 0, 0.5);
			color: #ffffff;
			text-align: center;
		}
	}
</style>